package com.matt.service.estimate.impl;

import com.dotflat.util.excelUtil.Constants;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.domain.estimate.CourseExtendEstimate;
import com.matt.domain.estimate.LikedRecord;
import com.matt.domain.estimate.dto.CourseEstimateDTO;
import com.matt.repository.estimate.CourseExtendEstimateRepository;
import com.matt.repository.estimate.LikedRecordRepository;
import com.matt.service.estimate.CourseEstimateService;
import com.matt.service.remoteCall.SsoCallService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CourseEstimateServiceImpl implements CourseEstimateService {

    @Autowired
    CourseExtendEstimateRepository courseExtendEstimateRepository;

    @Autowired
    LikedRecordRepository likedRecordRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis缓存 Hash/HashSort结构 key(estimateId 评论id) field(evaluatorId 点赞人id) value(bizType)
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<CourseEstimateDTO> getPage(String ticket, String courseId, Integer pageNum, Integer pageSize) {
        // 获取课程下所有评论
        List<CourseExtendEstimate> courseExtendEstimates = courseExtendEstimateRepository.listByCourseId(courseId);
        List<CourseExtendEstimate> extendEstimateList = courseExtendEstimates.stream().skip(pageNum * pageSize).limit(pageSize).collect(Collectors.toList());

        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);

        List<CourseEstimateDTO> courseEstimateDTOList = extendEstimateList.stream().map(e -> {
            CourseEstimateDTO courseEstimateDTO = new CourseEstimateDTO();
            BeanUtils.copyProperties(e, courseEstimateDTO);
            courseEstimateDTO.setLikedCount(e.getLikeCount());

            // 统计评价点赞总数
//            Integer count = likedRecordRepository.countByBizIdAndBizType(e.getId(), "1");
//            courseEstimateDTO.setLikedCount(count);

            // 查询Redis 获取点赞总数和用户是否点赞
//            Long likedCount = redisTemplate.opsForHash().size(e.getId());
            Boolean isLiked = redisTemplate.opsForSet().isMember(Constants.LIKE_RECORD + courseEstimateDTO.getId(), staffDTO.getId());
            courseEstimateDTO.setIsLiked(isLiked);

            StaffDTO evaluator = ssoCallService.getStaffDTO(ticket, e.getEvaluatorId());
            courseEstimateDTO.setRealName(evaluator.getRealName());
            courseEstimateDTO.setHeadImgUrl(evaluator.getHeadImgUrl());
            return courseEstimateDTO;
        }).collect(Collectors.toList());

        PageImpl<CourseEstimateDTO> page = new PageImpl<>(courseEstimateDTOList, PageRequest.of(pageNum, pageSize), courseExtendEstimates.size());
        return page;
    }

    @Override
    public CourseExtendEstimate addCourseExtendEstimate(String ticket, CourseExtendEstimate courseExtendEstimate) {
        Assert.notNull(courseExtendEstimate.getCourseId(), "课程id不能为空");
        Assert.notNull(courseExtendEstimate.getCourseContent(), "课程评价内容不能为空");

        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);
        courseExtendEstimate.setEvaluatorId(staffDTO.getId());

        courseExtendEstimate.setCreateDate(String.valueOf(LocalDate.now()));
        courseExtendEstimate.setLikeCount(0);

        courseExtendEstimateRepository.save(courseExtendEstimate);

//        EstimateStrategy estimateStrategy = StrategyContext.getEstimateStrategy(CourseEstimateStrategy.class.getSimpleName());
//        estimateStrategy.estimate(courseExtendEstimate.getCourseId(), courseExtendEstimate.getEvaluatorId(),
//                courseExtendEstimate.getCourseContent(), courseExtendEstimate.getCreateDate(), courseExtendEstimate.getImgUrl());
        return courseExtendEstimate;
    }

    @Override
    public CourseEstimateDTO updateCourseExtendEstimate(String ticket, CourseEstimateDTO courseEstimateDTO) {

//        courseExtendEstimateRepository.updateCourseEstimate(courseExtendEstimate.getId(), courseExtendEstimate.getCourseContent());

        return courseEstimateDTO;
    }

    @Override
    public CourseExtendEstimate deleteCourseExtendEstimate(String ticket, String courseId, String courseEstimateId) {
        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);
        // 删除点赞记录
        redisTemplate.opsForSet().remove(Constants.LIKE_RECORD + courseEstimateId, staffDTO.getId());

        likedRecordRepository.deleteLikedRecordByUserIdAndBizId(staffDTO.getId(), courseEstimateId);

        // 删除评论
        courseExtendEstimateRepository.deleteByCourseEstimateId(courseEstimateId);
        return null;
    }

    @Override
    @Transactional
    public CourseEstimateDTO like(String ticket, CourseEstimateDTO courseEstimateDTO) {
        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);

        LikedRecord likedRecord = new LikedRecord();
        likedRecord.setUserId(staffDTO.getId());
        likedRecord.setBizType("1");
        likedRecord.setBizId(courseEstimateDTO.getId());
        likedRecord.setCreateDate(String.valueOf(LocalDate.now()));

        CourseExtendEstimate courseExtendEstimate = courseExtendEstimateRepository.findById(courseEstimateDTO.getId()).get();

        if (Objects.equals(courseEstimateDTO.getIsLiked(), Boolean.TRUE)) {
            // 存入redis courseId userId
            redisTemplate.opsForSet().add(Constants.LIKE_RECORD + courseEstimateDTO.getId(), staffDTO.getId());
            // 新增点赞记录
            likedRecordRepository.save(likedRecord);

            // 点赞数量加一
            courseExtendEstimateRepository.increaseLikeCountById(courseEstimateDTO.getId());
        } else {
            // 取消点赞 删除redis记录
            redisTemplate.opsForSet().remove(Constants.LIKE_RECORD + courseEstimateDTO.getId(), staffDTO.getId());
            // 点赞记录表删除记录
//            likedRecordRepository.deleteLikedRecordByUserIdAndBizId(courseEstimateDTO.getId(), staffDTO.getId());

//            likedRecordRepository.delete(likedRecord);
            likedRecordRepository.deleteLikedRecordByUserIdAndBizId(staffDTO.getId(), courseEstimateDTO.getId());

            if (courseExtendEstimate.getLikeCount() >= 1) {
                // 点赞数量减一
                courseExtendEstimateRepository.decreaseLikeCountById(courseEstimateDTO.getId());
            }

        }
        return courseEstimateDTO;
    }
}
